<?php

namespace App\Http\Controllers\Admin;

use App\Utils\UploadUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UploadController extends AdminBaseController
{
    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadImage(Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|image|max:5120', // 5MB限制
            'directory' => 'string|max:100'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        try {
            $file = $request->file('file');
            $directory = $request->input('directory', 'images');
            
            // 使用上传工具类上传图片
            $result = UploadUtil::uploadImage($file, $directory);
            
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }
    
    /**
     * 批量上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchUploadImages(Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'images' => 'required|array',
            'images.*' => 'required|file|image|max:5120', // 5MB限制
            'directory' => 'string|max:100'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        try {
            $files = $request->file('images');
            $directory = $request->input('directory', 'images');
            
            $results = [];
            foreach ($files as $file) {
                $results[] = UploadUtil::uploadImage($file, $directory);
            }
            
            return $this->success($results);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }
}